/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "usb_device.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
#include <string.h>
#include "foc.h"
#include "pwm_curr.h"
#include "encoder.h"
#include "controller.h"
#include "mc_task.h"
#include "anticogging.h"
#include "usr_config.h"
#include "usart.h"
#include "serial.h"

#define CH_COUNT 10
struct Frame {
    float fdata[CH_COUNT];
    unsigned char tail[4];
};

struct Frame vfoaFrame = {
        .tail = {0x00, 0x00, 0x80, 0x7f}
};

uint8_t vofaCmdBuf[1024];
volatile uint32_t SystickCount = 0;
/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
#include "calibration.h"

volatile bool go = false;
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void) {
    /* USER CODE BEGIN 1 */

    /* USER CODE END 1 */

    /* MCU Configuration--------------------------------------------------------*/

    /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
    HAL_Init();

    /* USER CODE BEGIN Init */

    /* USER CODE END Init */

    /* Configure the system clock */
    SystemClock_Config();

    /* USER CODE BEGIN SysInit */

    /* USER CODE END SysInit */

    /* Initialize all configured peripherals */
    MX_GPIO_Init();
    MX_ADC1_Init();
    MX_ADC2_Init();
    MX_SPI1_Init();
    MX_TIM1_Init();
    MX_TIM6_Init();
    MX_USART3_UART_Init();
    MX_USB_Device_Init();
    /* USER CODE BEGIN 2 */

    while (!go) {}

    USR_CONFIG_set_default_config();

    HAL_Delay(500);


    USR_CONFIG_set_default_cogging_map();

    HAL_Delay(500);


    MCT_init();
    FOC_init();
    PWMC_init();
    ENCODER_init();
    CONTROLLER_init();

    // MCT_safety_task timer
    HAL_TIM_Base_Start_IT(&htim6);

    HAL_Delay(500);

    MCT_set_state(IDLE);

    HAL_GPIO_WritePin(nSLEEP_GPIO_Port, nSLEEP_Pin, 1);
    UsrConfig.control_mode = CONTROL_MODE_VELOCITY_RAMP;
    /* USER CODE END 2 */

    /* Infinite loop */
    /* USER CODE BEGIN WHILE */
    while (1) {
        MCT_low_priority_task();
        /* USER CODE END WHILE */

        /* USER CODE BEGIN 3 */
    }
    /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void) {
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

    /** Configure the main internal regulator output voltage
    */
    HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST);

    /** Initializes the RCC Oscillators according to the specified parameters
    * in the RCC_OscInitTypeDef structure.
    */
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI48 | RCC_OSCILLATORTYPE_HSE;
    RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS;
    RCC_OscInitStruct.HSI48State = RCC_HSI48_ON;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
    RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV3;
    RCC_OscInitStruct.PLL.PLLN = 85;
    RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
    RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
    RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
        Error_Handler();
    }

    /** Initializes the CPU, AHB and APB buses clocks
    */
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
                                  | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) {
        Error_Handler();
    }
}

/* USER CODE BEGIN 4 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {

    if (htim->Instance == TIM6) {
        MCT_safety_task();
        SystickCount++;
    }
}

#include "usbd_cdc_if.h"

/**
  * @brief  Injected conversion complete callback in non-blocking mode.
  * @param hadc ADC handle
  * @retval None
  */
extern volatile float mod_d_out;
extern volatile float mod_q_out;
extern volatile float phase_out;
extern volatile float every_plus;
extern volatile float sum_out;
extern volatile float div_out;
extern volatile int *p_error_arr;
extern volatile float error_out;
extern volatile float error_out_2;
extern volatile float step_out;

void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc) {
    /* Calc ADC offset */
    static int adc_sum_a = 0;
    static int adc_sum_b = 0;
    static int adc_sum_c = 0;
    static bool isCalcAdcOffsetOvered = false;
    const int measCnt = 64;
    static int measCntCopy = measCnt;
    if (hadc->Instance == ADC1 && !isCalcAdcOffsetOvered) {
        adc_sum_a += HAL_ADCEx_InjectedGetValue(&hadc1, ADC_INJECTED_RANK_1);
        adc_sum_b += HAL_ADCEx_InjectedGetValue(&hadc1, ADC_INJECTED_RANK_2);
        adc_sum_c += HAL_ADCEx_InjectedGetValue(&hadc1, ADC_INJECTED_RANK_3);

        if (--measCntCopy <= 0) {
            phase_a_adc_offset = adc_sum_a / measCnt;
            phase_b_adc_offset = adc_sum_b / measCnt;
            phase_c_adc_offset = adc_sum_c / measCnt;

            isCalcAdcOffsetOvered = true;
        }
    }

    if (hadc->Instance == ADC1 && isCalcAdcOffsetOvered) {
        MCT_high_frequency_task();


        vfoaFrame.fdata[0] = Foc.i_a;
        vfoaFrame.fdata[1] = Foc.i_b;
        vfoaFrame.fdata[2] = Foc.i_c;
        vfoaFrame.fdata[3] = UsrConfig.encoder_dir;
        vfoaFrame.fdata[4] = (float) UsrConfig.encoder_offset;
        vfoaFrame.fdata[5] = step_out;
        vfoaFrame.fdata[6] = Controller.vel_setpoint;
        vfoaFrame.fdata[7] = Encoder.vel;
        vfoaFrame.fdata[8] = Controller.input_velocity;

        if (StatuswordNew.errors.over_current == 1)
            vfoaFrame.fdata[9] = 1;
        else if (StatuswordNew.errors.over_voltage == 1)
            vfoaFrame.fdata[9] = 2;
        else if (StatuswordNew.errors.under_voltage == 1)
            vfoaFrame.fdata[9] = 3;
        else if (StatuswordNew.errors.adc_selftest_fatal == 1)
            vfoaFrame.fdata[9] = 4;
        else if (StatuswordNew.errors.encoder_offline == 1)
            vfoaFrame.fdata[9] = 5;
        else if (StatuswordNew.errors.PADDING_1 == 1)
            vfoaFrame.fdata[9] = 6;
        else if (StatuswordNew.errors.PADDING_2 == 1)
            vfoaFrame.fdata[9] = 7;
        else
            vfoaFrame.fdata[9] = 0;
        CDC_Transmit_FS((uint8_t *) &vfoaFrame, sizeof(vfoaFrame));
        //HAL_UART_Transmit_DMA(&huart3, (uint8_t *) (&vfoaFrame), sizeof(vfoaFrame));
    }
}


/**
 * @brief Parse vofa cmd
 * @param cmdBuf
 * @return
 */
static float vofa_cmd_parse(uint8_t *cmdBuf, char *arg) {
    return atof(cmdBuf + strlen(arg));
}

void usb_cb(uint8_t *buf) {
//    Controller.input_velocity_buffer
    if (strstr(buf, "calib")) {
        MCT_set_state(CALIBRATION);
    } else if (strstr(buf, "run=")) {
        float val = vofa_cmd_parse(buf, "run=");
        if (val > 0) {
            Controller.input_velocity = val;
            MCT_set_state(RUN);
        } else
            MCT_set_state(IDLE);
    } else if (strstr(buf, "anticog")) {
        MCT_set_state(ANTICOGGING);
    } else if (strstr(buf, "rsetErr")) {
        MCT_reset_error();
    } else if (strstr(buf, "torque")) {
        float val = vofa_cmd_parse(buf, "torque=");
        Controller.input_torque_buffer = val;
        CONTROLLER_sync_callback();
    } else if (strstr(buf, "vel")) {
        float val = vofa_cmd_parse(buf, "vel=");
        Controller.input_velocity_buffer = val;
        CONTROLLER_sync_callback();
    } else if (strstr(buf, "pos")) {
        float val = vofa_cmd_parse(buf, "pos=");
        Controller.input_position_buffer = val;
        CONTROLLER_sync_callback();
    } else if (strstr(buf, "gogogo")) {
        go = true;
    }
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void) {
    /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */
    __disable_irq();
    while (1) {
    }
    /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
